﻿using Abp.Application.Services.Dto;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.Runtime.Session;
using Abp.UI;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Bom;
using Camc.Quality.Common;
using Camc.Quality.DataDictionary;
using Camc.Quality.Dto;
using Camc.Quality.IOperationHistory;
using Camc.Quality.Materials;
using Camc.Quality.OperationHistory;
using Camc.Quality.Quality;
using Camc.Quality.StoreManagement.StoragePut;
using Camc.Quality.StoreManagement.StoreInfo;
using Camc.Quality.TrepanningManager.BomAnalyseDto;
using Camc.Quality.TrepanningManager.BomNestingInterface;
using Camc.Quality.TrepanningManager.CollectBom;
using Camc.Quality.TrepanningManager.MatingManager;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using static Camc.Quality.StoreManagement.StoragePut.StoreStockContent;
using static Camc.Quality.TrepanningManager.BomAnalyse.BomAnalyseEnum;

namespace Camc.Quality.TrepanningManager.BomAnalyse
{
    public class BomAnalyseAppService : QualityAppServiceBase
    {
        private readonly IRepository<MaterialsContent, Guid> _materialsContentRepository;
        private readonly IRepository<BomDesign, Guid> _bomDesignRepository;
        private readonly IRepository<BomDesignDetail, Guid> _bomDesignDetailRepository;
        private readonly IRepository<CollectBomManager, Guid> _collectBomManagerRepository;
        private readonly IRepository<StoreStock, Guid> _storeStockpository;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        private readonly IRepository<StoreStockContent, Guid> _storeStockContentRepository;
        private readonly IRepository<BomAnalyseContent, Guid> _bomAnalyseContentRepository;
        private readonly IBomAnalyseExportToExcel _bomAnalyseExportToExcel;
        private readonly IAbpSession _abpSession;
        private readonly IRepository<MaterialsNode, Guid> _materialsNoderepository;
        public readonly IRepository<StorePutContent, Guid> _storePutContentRepository;
        private readonly IRepository<CollectBomManagerChild, Guid> _collectBomManagerChildRepository;
        private readonly CollectBomAppService _collectBomAppService;
        public  List<StoreStockContent> storeStocks = new List<StoreStockContent>();
        private readonly IOperationHistoryAppService _iOperationHistoryAppService;
        public BomAnalyseAppService(IRepository<MaterialsContent, Guid> materialsContentRepository, IRepository<BomDesign, Guid> bomDesignrepository, IRepository<BomDesignDetail, Guid> bomDesignDetailrepository, IRepository<User, long> userRepository, IRepository<CollectBomManager, Guid> collectBomManagerrepository, IRepository<StoreStockContent, Guid> storeStockContentRepository, IRepository<BomAnalyseContent, Guid> bomAnalyseContentRepository, IRepository<StoreStock, Guid> storeStockpository, IRepository<Sys_Code, Guid> sysCodeRepository, IRepository<MaterialsNode, Guid> materialsNoderepository, IRepository<StorePutContent, Guid> storePutContentRepository, IAbpSession abpSession, IBomAnalyseExportToExcel bomAnalyseExportToExcel, IRepository<CollectBomManagerChild, Guid> collectBomManagerChildRepository, CollectBomAppService collectBomAppService, IOperationHistoryAppService iOperationHistoryAppService)
        {
            this._materialsContentRepository = materialsContentRepository;
            this._bomDesignRepository = bomDesignrepository;
            this._bomDesignDetailRepository = bomDesignDetailrepository;
            this._userRepository = userRepository;
            this._collectBomManagerRepository = collectBomManagerrepository;
            this._storeStockContentRepository = storeStockContentRepository;
            this._bomAnalyseContentRepository = bomAnalyseContentRepository;
            this._storeStockpository = storeStockpository;
            this._sysCodeRepository = sysCodeRepository;
            this._materialsNoderepository = materialsNoderepository;
            this._storePutContentRepository = storePutContentRepository;
            this._abpSession = abpSession;
            this._bomAnalyseExportToExcel = bomAnalyseExportToExcel;
            this._collectBomManagerChildRepository = collectBomManagerChildRepository;
            this._collectBomAppService = collectBomAppService;
            this._iOperationHistoryAppService = iOperationHistoryAppService;
        }
        /// <summary>
        /// 查询配套数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<BomAnalyseContentDto>> GetBomAalyseContent(BomAnalyseManagerEditDto input)
        {
            if (input != null)
            {
                BomAnalyseContentDto bomAnalyseContentDto = new BomAnalyseContentDto();
                if (input.ModuleId == Guid.Empty)
                {
                    return new PagedResultDto<BomAnalyseContentDto>();
                }
                var queryCollectBomManagerData = _collectBomManagerRepository.FirstOrDefaultAsync(t => t.ModuleId == input.ModuleId && t.SendTimeId == input.SendTimeId && t.XJId == input.XJId).Result;
                if (queryCollectBomManagerData == null) { return null; }
                //找出对应的芯级
                var queryBomDesignXj = _bomDesignDetailRepository.FirstOrDefaultAsync(t => t.Id == queryCollectBomManagerData.XJId && t.ParentId == Guid.Empty).Result;
                //找出BomdesignId 根据bomdesignID 找出芯级下的所有物料  因为可能存在相同物料 所以加Distinct
                //var queryBomDesignData = _collectBomManagerChildRepository.GetAll().Where(t => t.BomDesignId == queryCollectBomManagerData.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件 && t.LevelRelationship.StartsWith(queryBomDesignXj.LevelRelationship)).Distinct();
                var queryBomDesignData = await _collectBomAppService.GetCollectBomMaterialsContentNB(input.XJId);
                var querysStoreStockContent = _storeStockContentRepository.GetAll();
                if (queryBomDesignData == null)
                {
                    bomAnalyseContentDto.Message = "请先汇总数据";
                    bomAnalyseContentDto.code = 1;
                    return new PagedResultDto<BomAnalyseContentDto>();
                }
                //计算可用预配套数量（符合条件的没有配套的可用数量）&& DateTime.Parse(t.ExpirationDate) > DateTime.Now 
                //&& DateTime.Parse(t.ExpirationDate) > DateTime.Now && t.ProductCodeId.Contains(input.ModuleId.ToString())
                // 物料建模中的 物料id 和 仓库主表id相同 因为 入库时 会和物料建模中的id相关连  找出当前型号发次 芯级下的和设计bom对应的所有物料信息 定位到 适用于当前发次型号芯级仓库下的 这个物料详细信息
                //DateTime dte = DateTime.Parse("2021-10-29T16:00:00.000Z");&& DateTime.Parse(t.ExpirationDate) > DateTime.Now
                //var cc = _storeStockContentRepository.GetAll().FirstOrDefaultAsync().Result;
                //DateTime dt = DateTime.Parse(cc.ExpirationDate);
                //if (dt > DateTime.Now)
                //{

                //}
                //计算没有预配套的物料信息
                var storeStocksContent = from queryMaterislsContent in _materialsContentRepository.GetAll()
                                         join queryStoreStocks in _storeStockpository.GetAll() on
                                           new { no = queryMaterislsContent.Id, mod = input.StoreId } equals new { no = queryStoreStocks.MaterialsContentId, mod = queryStoreStocks.StoreId }
                                         join queryStoreStockContents in querysStoreStockContent.
                                         Where(t =>( (t.SendTimeId.Contains(input.SendTimeId.ToString().ToUpper()) && t.ProductCodeId.Contains(input.ModuleId.ToString().ToUpper()))||t.ProductCode.Contains(input.Module + "系列")) && t.Batch == "01"    && (DateTime.Parse(t.ExpirationDate)) > DateTime.Now && t.BomAnalysecontentId == null && (t.MaterialsProperty == StoreManagement.MaterialsPropertys.正常品 || t.MaterialsProperty == StoreManagement.MaterialsPropertys.返修正常品)) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                         where queryStoreStockContents.IsPreSuit == IsSuits.否
                                         //join bomDesignDetailData in queryBomDesignData on queryMaterislsContent.Id equals bomDesignDetailData.MaterialId
                                         select queryStoreStockContents;
                //后期去掉没用
                if (storeStocksContent != null && storeStocksContent.Count() > 0)
                {
                    storeStocks = storeStocksContent.ToList();
                }
                //var cafa = storeStocks.Where(t => t.MaterialsContentId ==Guid.Parse("9EAAC00C-BB07-4DBC-1E3C-08D9A5845FCC"));
                //查询芯级下的所有配套数据
                var queryCollectMatingNumber = from queryloadContent in _materialsContentRepository.GetAll()
                                               join queryStoreStocks in _storeStockpository.GetAll() on
                                                 queryloadContent.Id equals queryStoreStocks.MaterialsContentId
                                               join queryStoreStockContents in querysStoreStockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == queryCollectBomManagerData.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                               select queryStoreStockContents;
                //计算自由库存数量
                var quaryzyKuCun = from queryStoreStockContent in querysStoreStockContent.Where(t => t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null ||(t.MaterialsProperty != StoreManagement.MaterialsPropertys.正常品 && t.MaterialsProperty != StoreManagement.MaterialsPropertys.返修正常品))
                                   join queryStoreStock in _storeStockpository.GetAll() on queryStoreStockContent.StoreStockId equals queryStoreStock.Id
                                   where queryStoreStockContent.StoreId == input.StoreId
                                   select queryStoreStockContent;
          //      var cou = quaryzyKuCun.Where(t => t.ProductDrawingNo == "Q/Y70.1" && t.StoreStockId==Guid.Parse("e6586db6-1280-492a-a87d-e310182a8032"));

                ////查询对应系列入库物料
                //var queryKuCunXl = from queryMaterislsContent in _materialsContentRepository.GetAll()
                //                         join queryStoreStocks in _storeStockpository.GetAll() on
                //                           new { no = queryMaterislsContent.Id, mod = input.StoreId } equals new { no = queryStoreStocks.MaterialsContentId, mod = queryStoreStocks.StoreId }
                //                         join queryStoreStockContents in querysStoreStockContent.
                //                         Where(t => t.ProductCode.Contains(input.Module + "系列") && t.Batch == "01" && t.IsPreSuit == IsSuits.否  && (DateTime.Parse(t.ExpirationDate)) > DateTime.Now && t.BomAnalysecontentId == null && (t.MaterialsProperty == StoreManagement.MaterialsPropertys.正常品 || t.MaterialsProperty == StoreManagement.MaterialsPropertys.返修正常品)) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                //                         //join bomDesignDetailData in queryBomDesignData on queryMaterislsContent.Id equals bomDesignDetailData.MaterialId
                //                         select queryStoreStockContents;
                ////QY70.1 系列物料数量
                //var caf = queryKuCunXl.Where(t=>t.StoreStockId==Guid.Parse("e6586db6-1280-492a-a87d-e310182a8032"));
                //string sql = storeStocksContent.ToSql();
                //计算该零件工预配套数量 计算自由库存数量
                var materalisCount = from queryMaterislsContent in _materialsContentRepository.GetAll()
                                     join queryStoreStocks in _storeStockpository.GetAll()
                                     on new { no = queryMaterislsContent.Id, mod = input.StoreId } equals new { no = queryStoreStocks.MaterialsContentId, mod = queryStoreStocks.StoreId }
                                     join queryStoreStockContents in querysStoreStockContent.Where(t => ((t.SendTimeId.Contains(input.SendTimeId.ToString().ToUpper()) && t.ProductCodeId.Contains(input.ModuleId.ToString().ToUpper()))|| t.ProductCode.Contains(input.Module + "系列")) && t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                     //join bomDesignDetailData in queryBomDesignData on queryMaterislsContent.Id equals bomDesignDetailData.MaterialId
                                     select queryStoreStockContents;
                //计算该零件工预配套数量 计算自由库存数量
                //var materalisCount = from queryMaterislsContent in _materialsContentRepository.GetAll()
                //                     join queryStoreStocks in _storeStockpository.GetAll()
                //                     on new { no = queryMaterislsContent.Id, mod = input.StoreId } equals new { no = queryStoreStocks.MaterialsContentId, mod = queryStoreStocks.StoreId }
                //                     join queryStoreStockContents in _storeStockContentRepository.GetAll().Where(t => t.StoreStockId ==input.StoreId && t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                //                     //join bomDesignDetailData in queryBomDesignData on queryMaterislsContent.Id equals bomDesignDetailData.MaterialId
                //                     select queryStoreStockContents;
                //var asf = materalisCount.ToList();
                //int count = asf.Count;
                //计算根据芯级已经预配套的数量&& DateTime.Parse(t.ExpirationDate) > DateTime.Now
                var queryCollectNumber = materalisCount.Where(t => t.BomAnalysecontentId == queryCollectBomManagerData.Id);
                var queryBomAnalyseContentsGoupy = from queryMaterislsContent in queryBomDesignData.AsQueryable()
                                                   join queryStoreStocks in _storeStockpository.GetAll()
                                                   on new { no = queryMaterislsContent.MerialsId, mod = input.StoreId } equals new { no = queryStoreStocks.MaterialsContentId, mod = queryStoreStocks.StoreId } into store
                                                   from sr in store.DefaultIfEmpty()
                                                       //join queryStoreStockContents in _storeStockContentRepository.GetAll() on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId

                                                   select new BomAnalyseContentDto
                                                   {
                                                       MaterialsContentId = queryMaterislsContent.MerialsId,
                                                       BomDosageTotalAmount = queryMaterislsContent.Unit1BomDosageXj,
                                                       CollectBomManagerId = queryMaterislsContent.Id,
                                                       YearsNo = queryMaterislsContent.YearsNo
                                                   };


                //var cc = from queryMaterislsContent in _materialsContentRepository.GetAll()
                //         join queryStoreStocks in _storeStockpository.GetAll() on
                //                             new { no = queryMaterislsContent.Id, mod = input.StoreId } equals new { no = queryStoreStocks.MaterialsContentId, mod = queryStoreStocks.StoreId }
                //                              //join queryStoreStockContents in _storeStockContentRepository.GetAll() on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                //         join bomgroup in queryBomAnalyseContentsGoupy on queryMaterislsContent.Id equals bomgroup.MaterialsContentId

                //         //join bomAnalyseContent in _bomAnalyseContentRepository.GetAll() on
                //         //new { no = queryMaterislsContent.MaterialNo, mod = queryMaterislsContent.Model } equals new { no = bomAnalyseContent.MaterialNo, mod = bomAnalyseContent.Module } into bomAnalyse
                //         //from bly in bomAnalyse.DefaultIfEmpty()
                //         //join queryNode in _materialsNoderepository.GetAll().WhereIf(!input.MaterialTypeName.IsNullOrWhiteSpace(), t => t.MaterialTypeName.StartsWith(input.MaterialTypeName)) on queryMaterislsContent.MaterialsNodeId equals queryNode.Id
                //         //join queryNodeChild in _materialsNoderepository.GetAll() on queryMaterislsContent.MaterialCategoryId equals queryNodeChild.Id
                //         //join code in _sysCodeRepository.GetAll() on queryMaterislsContent.UnitId equals code.Id
                //         //into codeData
                //         from cd in codeData.DefaultIfEmpty()
                //         select queryMaterislsContent;
                 

                //关联物料建模 和 仓库库存信息
                var queryBomAnalyseContents = (from queryMaterislsContent in _materialsContentRepository.GetAll()
                                               join queryStoreStocks in _storeStockpository.GetAll()
                                               on new { no = queryMaterislsContent.Id, mod = input.StoreId } equals new { no = queryStoreStocks.MaterialsContentId, mod = queryStoreStocks.StoreId }
                                              //join queryStoreStockContents in _storeStockContentRepository.GetAll() on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                               join bomgroup in queryBomAnalyseContentsGoupy on queryMaterislsContent.Id equals bomgroup.MaterialsContentId

                                               //join bomAnalyseContent in _bomAnalyseContentRepository.GetAll() on
                                               //new { no = queryMaterislsContent.MaterialNo, mod = queryMaterislsContent.Model } equals new { no = bomAnalyseContent.MaterialNo, mod = bomAnalyseContent.Module } into bomAnalyse
                                               //from bly in bomAnalyse.DefaultIfEmpty()
                                               join queryNode in _materialsNoderepository.GetAll().WhereIf(!input.MaterialTypeName.IsNullOrWhiteSpace(), t => t.MaterialTypeName.StartsWith(input.MaterialTypeName)) on queryMaterislsContent.MaterialsNodeId equals queryNode.Id
                                               join queryNodeChild in _materialsNoderepository.GetAll() on queryMaterislsContent.MaterialCategoryId equals queryNodeChild.Id
                                               join code in _sysCodeRepository.GetAll() on queryMaterislsContent.UnitId equals code.Id
                                               into codeData
                                               from cd in codeData.DefaultIfEmpty()
                                               select new BomAnalyseContentDto
                                               {
                                                   // CollectBomManagerId = queryCollectBomManagerData.Id,
                                                   HJXH = input.Module,
                                                   HJFC = input.SendTime,
                                                   Id = queryStoreStocks.Id,
                                                   XJCode = queryCollectBomManagerData.XJDrawingNo,
                                                   XJName = queryCollectBomManagerData.XJName,
                                                   StoreStockId = queryStoreStocks.Id,
                                                   //YearsNo = ,
                                                   XJId = input.XJId,
                                                   ModuleId = input.ModuleId,
                                                   SendTimeId = input.SendTimeId,
                                                   StoreId = input.StoreId,
                                                   MaterialNo = queryMaterislsContent.MaterialNo,
                                                   MaterialName = queryMaterislsContent.MaterialName,
                                                   Module = queryMaterislsContent.Model,
                                                   UnitName = cd.Description,
                                                   MaterialsContentId = queryMaterislsContent.Id,
                                                   BomDosageTotalAmount = bomgroup.BomDosageTotalAmount,
                                                   CollectBomManagerId = bomgroup.CollectBomManagerId,
                                                   SuiteStock = queryCollectMatingNumber.Count(t => t.StoreStockId == queryStoreStocks.Id),
                                                   //可用库存数量 自由库存数量中符合条件可自动配套的产品数量 (queryStoreStockContentList.Count(t => t.StoreStockId == queryStoreStocks.Id) 
                                                   //storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) < queryStoreStocks.UsableQuantityStock ? queryStoreStocks.UsableQuantityStock - storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) : 
                                                   UsableQuantityStock = storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id),
                                                  // + queryKuCunXl.Count(t => t.MaterialsContentId == queryMaterislsContent.Id && t.ProductCode == input.Module + "系列"),
                                                   //+ queryKuCunXl.Count(t=>t.StoreStockId==queryStoreStocks.Id&&t.MaterialsContentId== queryMaterislsContent.Id),
                                                   //物料类型
                                                   MaterialTypeName = queryNode.MaterialTypeName,
                                                   //物料细类
                                                   MaterialCategoryName = queryNodeChild.MaterialTypeName,
                                                   // 自由库存数量（库存未预配套的数量）==总数量-预配套数量? 
                                                   FreeQuantityStock = (queryStoreStocks.TotalQuantity - (quaryzyKuCun.Count(t => t.StoreStockId == queryStoreStocks.Id))),
                                                   //+ queryKuCunXl.Count(t => t.MaterialsContentId == queryMaterislsContent.Id&&t.ProductCode == input.Module+"系列"),
                                                   //&& queryStoreStocks.ProductNumber.Contains(t.ProductNumber)
                                                   //预配套数量&& queryStoreStocks.ProductNumber.Contains(t.ProductNumber)
                                                   PreSuiteStock = queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id),
                                                   //预配套调整数&& queryStoreStocks.ProductNumber.Contains(t.ProductNumber)
                                                   // && queryStoreStocks.ProductNumber.Contains(t.ProductNumber)
                                                   CompleteAdjust = queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) > bomgroup.BomDosageTotalAmount ? bomgroup.BomDosageTotalAmount - queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) : 0,
                                                   //缺料数量 芯级用量 - 预配套数量 大于可用与库存数量 那么就是缺料&& queryStoreStocks.ProductNumber.Contains(t.ProductNumber)
                                                   StarvingStock = (bomgroup.BomDosageTotalAmount - queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id)) > storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) ? bomgroup.BomDosageTotalAmount - (storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) + queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id)) : 0,
                                                   //出库数量
                                                   DeliveryStock = queryCollectMatingNumber.Count(t => t.StoreStockId == queryStoreStocks.Id && t.OutboundState == OutboundStates.出库),
                                                   //预配套人
                                                   PreSuiteName = "",
                                                   //预配套时间
                                                   PreSuiteTime = "",
                                                   ProductNumber = queryStoreStocks.ProductNumber,
                                                   //入库主表ID
                                                   // StoreStockId = queryStoreStockContent.Id,
                                                   //发次
                                                   //SendTime = queryStoreStockContents.SendTime,
                                                   ////产品图号
                                                   //ProductCode = queryStoreStockContents.ProductCode,&& queryStoreStocks.ProductNumber.Contains(t.ProductNumber)
                                                   PreSuiteStatus = bomgroup.BomDosageTotalAmount - queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) > storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) ? (int)CompleteStatus.缺料 :
                                                   queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) == 0 ? (int)CompleteStatus.未预配套 :
                                                   bomgroup.BomDosageTotalAmount - queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) <= storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id)&& bomgroup.BomDosageTotalAmount - queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) <= storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) && storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) != 0 && bomgroup.BomDosageTotalAmount > queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) ? (int)CompleteStatus.预配套中 : bomgroup.BomDosageTotalAmount == queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) ? (int)CompleteStatus.已预配套 : 0,
                                                   //预配套状态
                                                   PreSuiteStatusName = bomgroup.BomDosageTotalAmount - queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) > storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id)? CompleteStatus.缺料.ToString() : queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) == 0 ? CompleteStatus.未预配套.ToString() : bomgroup.BomDosageTotalAmount - queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) <= storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) && bomgroup.BomDosageTotalAmount - queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) <= storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) && storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) != 0 && bomgroup.BomDosageTotalAmount > queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) ? CompleteStatus.预配套中.ToString() : bomgroup.BomDosageTotalAmount == queryCollectNumber.Count(t => t.StoreStockId == queryStoreStocks.Id) ? CompleteStatus.已预配套.ToString() : "",
                                                   YearsNo = bomgroup.YearsNo
                                               }).ToList();

                //var filterlistAll = queryBomAnalyseContents.ToList();

                //var queryUnion = from queryBomGroup in queryBomAnalyseContentsGoupy
                //                 join
                //                    filterData in filterlistAll on queryBomGroup.MaterialsContentId equals filterData.MaterialsContentId
                //                 select new BomAnalyseContentDto
                //                 {
                //                     CollectBomManagerId = queryCollectBomManagerData.Id,
                //                     HJXH = input.Module,
                //                     HJFC = input.SendTime,
                //                     Id = filterData.Id,
                //                     XJCode = queryCollectBomManagerData.XJDrawingNo,
                //                     XJName = queryCollectBomManagerData.XJName,
                //                     StoreStockId = filterData.StoreStockId,
                //                     XJId = input.XJId,
                //                     ModuleId = input.ModuleId,
                //                     SendTimeId = input.SendTimeId,
                //                     StoreId = input.StoreId,
                //                     MaterialNo = filterData.MaterialNo,
                //                     MaterialName = filterData.MaterialName,
                //                     Module = filterData.Module,
                //                     UnitName = filterData.UnitName,
                //                     MaterialsContentId = filterData.MaterialsContentId,
                //                     BomDosageTotalAmount = queryBomGroup == null ? 0 : queryBomGroup.BomDosageTotalAmount,
                //                     //可用库存数量 自由库存数量中符合条件可自动配套的产品数量 (queryStoreStockContentList.Count(t => t.StoreStockId == queryStoreStocks.Id) 
                //                     //storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) < queryStoreStocks.UsableQuantityStock ? queryStoreStocks.UsableQuantityStock - storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) : 
                //                     UsableQuantityStock = filterData.UsableQuantityStock,
                //                     //物料类型
                //                     MaterialTypeName = filterData.MaterialTypeName,
                //                     //物料细类
                //                     MaterialCategoryName = filterData.MaterialCategoryName,
                //                     // 自由库存数量（库存未预配套的数量）==总数量-预配套数量?
                //                     FreeQuantityStock = filterData.FreeQuantityStock,
                //                     //预配套数量
                //                     PreSuiteStock = filterData.PreSuiteStock,
                //                     //预配套调整数
                //                     CompleteAdjust = filterData.CompleteAdjust,
                //                     //缺料数量 芯级用量 - 预配套数量 大于可用与库存数量 那么就是缺料
                //                     StarvingStock = (queryBomGroup.BomDosageTotalAmount - queryCollectNumber.Count(t => t.StoreStockId == filterData.StoreStockId)) > storeStocks.Count(t => t.StoreStockId == filterData.StoreStockId) ? queryBomGroup.BomDosageTotalAmount - (storeStocks.Count(t => t.StoreStockId == filterData.StoreStockId) + queryCollectNumber.Count(t => t.StoreStockId == filterData.StoreStockId && filterData.ProductNumber.Contains(t.ProductNumber))) : 0,
                //                     //出库数量
                //                     DeliveryStock = filterData.DeliveryStock,
                //                     //预配套人
                //                     PreSuiteName = filterData.PreSuiteName,
                //                     //预配套时间
                //                     PreSuiteTime = filterData.PreSuiteTime.ToString(),
                //                     ProductNumber = filterData.ProductNumber,
                //                     //入库主表ID
                //                     // StoreStockId = queryStoreStockContent.Id,
                //                     //发次
                //                     //SendTime = queryStoreStockContents.SendTime,
                //                     ////产品图号
                //                     //ProductCode = queryStoreStockContents.ProductCode,
                //                     PreSuiteStatus = filterData.PreSuiteStatus,
                //                     //预配套状态
                //                     PreSuiteStatusName = filterData.PreSuiteStatusName
                //                 };


                var queryList = (from queryBomGroup in queryBomDesignData.ToList()
                                 join filterData in queryBomAnalyseContents on new { no = queryBomGroup == null ? "" : queryBomGroup.MaterialNo, mod = queryBomGroup == null ? "" : queryBomGroup.Model } equals new { no = filterData == null ? "" : filterData.MaterialNo, mod = filterData == null ? "" : filterData.Module }
                                 into qug
                                 from qu in qug.DefaultIfEmpty()
                                 select new BomAnalyseContentDto
                                 {
                                     CollectBomManagerId = queryCollectBomManagerData.Id,
                                     HJXH = input.Module,
                                     HJFC = input.SendTime,
                                     Id = qu == null ? Guid.Empty : qu.Id,
                                     XJCode = queryCollectBomManagerData.XJDrawingNo,
                                     XJName = queryCollectBomManagerData.XJName,
                                     StoreStockId = qu == null ? Guid.Empty : qu.StoreStockId,
                                     XJId = input.XJId,
                                     ModuleId = input.ModuleId,
                                     SendTimeId = input.SendTimeId,
                                     StoreId = input.StoreId,
                                     MaterialNo = qu == null ? queryBomGroup.MaterialNo : qu.MaterialNo,
                                     MaterialName = qu == null ? queryBomGroup.MaterialName : qu.MaterialName,
                                     Module = qu == null ? queryBomGroup.Model : qu.Module,
                                     UnitName = qu == null ? queryBomGroup.Unit : qu.UnitName,
                                     MaterialsContentId = qu == null ? Guid.Empty : qu.MaterialsContentId,
                                     BomDosageTotalAmount = qu == null ? queryBomGroup.Unit1BomDosageXj : qu.BomDosageTotalAmount,
                                     //可用库存数量 自由库存数量中符合条件可自动配套的产品数量 (queryStoreStockContentList.Count(t => t.StoreStockId == queryStoreStocks.Id) 
                                     //storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) < queryStoreStocks.UsableQuantityStock ? queryStoreStocks.UsableQuantityStock - storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) : 
                                     UsableQuantityStock = qu == null ? 0 : qu.UsableQuantityStock,
                                     //物料类型
                                     MaterialTypeName = qu == null ? queryBomGroup.MaterialTypeName : qu.MaterialTypeName,
                                     //物料细类
                                     MaterialCategoryName = qu == null ? queryBomGroup.MaterialCategoryName : qu.MaterialCategoryName,
                                     // 自由库存数量（库存未预配套的数量）==总数量-预配套数量?
                                     FreeQuantityStock = qu == null ? 0 : qu.FreeQuantityStock,
                                     //预配套数量
                                     PreSuiteStock = qu == null ? 0 : qu.PreSuiteStock,
                                     //预配套调整数
                                     CompleteAdjust = qu == null ? 0 : qu.CompleteAdjust,
                                     //缺料数量 芯级用量 - 预配套数量 大于可用与库存数量 那么就是缺料
                                     StarvingStock = qu == null ? 0 : qu.StarvingStock,
                                     //出库数量
                                     DeliveryStock = qu == null ? 0 : qu.DeliveryStock,
                                     //预配套人
                                     PreSuiteName = qu == null ? "" : queryCollectNumber.FirstOrDefault(t => t.StoreStockId == qu.Id && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null) != null ? queryCollectNumber.FirstOrDefault(t => t.StoreStockId == qu.Id && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null).PreSuiteName : "",
                                     //预配套时间
                                     PreSuiteTime = qu == null ? "" : queryCollectNumber.FirstOrDefault(t => t.StoreStockId == qu.Id && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null) != null ? queryCollectNumber.FirstOrDefault(t => t.StoreStockId == qu.Id && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null).PreSuiteTime.ToString() : "",
                                     ProductNumber = qu == null ? "" : qu.ProductNumber,
                                     YearsNo = queryBomGroup == null ? "" : queryBomGroup.YearsNo,
                                     //入库主表ID
                                     // StoreStockId = queryStoreStockContent.Id,
                                     //发次
                                     //SendTime = queryStoreStockContents.SendTime,
                                     ////产品图号
                                     //ProductCode = queryStoreStockContents.ProductCode,
                                     PreSuiteStatus = qu == null ? 1 : qu.PreSuiteStatus,
                                     //预配套状态
                                     PreSuiteStatusName = qu == null ? "仓库无物料" : qu.PreSuiteStatusName,

                                 }).ToList();

                queryList = queryList.WhereIf(!string.IsNullOrEmpty(input.PreSuiteStatus), s => s.PreSuiteStatusName == input.PreSuiteStatus)
                    .WhereIf(!string.IsNullOrEmpty(input.MaterialTypeName), s => s.MaterialTypeName.Contains(input.MaterialTypeName)).ToList();
                if (queryList != null)
                {
                    try
                    {
                        var bomMakeContentDataList = queryList.AsQueryable().OrderBy(d => d.MaterialNo).OrderBy(s => s.Module).PageBy(input).ToList();
                        var listNew = ObjectMapper.Map<List<BomAnalyseContentDto>>(bomMakeContentDataList);
                        return new PagedResultDto<BomAnalyseContentDto>(queryList.Count(), listNew);
                    }
                    catch (Exception ex)
                    {
                        throw new UserFriendlyException("系统内部错误,请重试或联系管理员");
                    }
                }
                else
                {
                    throw new UserFriendlyException("无对应数据");
                }
            }
            //先查询汇总bom 是否有对应数据  
            return new PagedResultDto<BomAnalyseContentDto>();
        }
        //GetUsableQuantity(queryStoreStocks.TotalQuantity, queryStoreStockContents.ProductCode, queryStoreStockContents.SendTime, queryStoreStockContents.Batch, queryStoreStockContents.ExpirationDate, queryMaterislsContent.Model, queryMaterislsContent.MaterialNo),
        //GetPreStatus(queryStoreStocks.PreSuiteStock, bomDesignDetailData.BomDosageTotalAmount, GetUsableQuantity(queryStoreStocks.TotalQuantity, queryStoreStockContents.ProductCode, queryStoreStockContents.SendTime, queryStoreStockContents.Batch, queryStoreStockContents.ExpirationDate, queryMaterislsContent.Model, queryMaterislsContent.MaterialNo)),
        /// <summary>
        /// 得到预配套状态
        /// </summary>
        /// <param name="preSuiteStock">预配套数量</param>
        /// <param name="bomDosageTotalAmount">芯级用量</param>
        /// <param name="usableQuantityStock">可用库存数量</param>
        /// <returns></returns>
        public int GetPreStatus(decimal preSuiteStock, decimal bomDosageTotalAmount, decimal usableQuantityStock)
        {
            if (preSuiteStock == 0)
            {
                return (int)CompleteStatus.未预配套;
            }
            else if (bomDosageTotalAmount - preSuiteStock <= usableQuantityStock)
            {
                return (int)CompleteStatus.预配套中;
            }
            else if (bomDosageTotalAmount == preSuiteStock)
            {
                return (int)CompleteStatus.已预配套;
            }
            else if (bomDosageTotalAmount - preSuiteStock > usableQuantityStock)
            {
                return (int)CompleteStatus.缺料;
            }
            return 0;
        }
        /// <summary>
        /// 计算库存可用数量
        /// </summary>
        /// <param name="count">自由库存数量</param>
        /// <param name="code">型号</param>
        /// <param name="sendTime">发次</param>
        /// <param name="batch">批次</param>
        /// <param name="date">有效期</param>
        /// <param name="module">规格</param>
        /// <param name="no">图号</param>
        /// <returns></returns>
        private int GetUsableQuantity(int count, string code, string sendTime, string batch, string date, string module, string no)
        {
            //根据图号和规格 查询出 库存子表的 批次 和有效期大于今天的数据 
            var queryStoreStockContent = _storeStockContentRepository.GetAll().Where(t => t.ProductDrawingNo == no && t.Module == module && t.Batch == "01" && DateTime.Parse(t.ExpirationDate) > DateTime.Now && t.SendTimeId.Contains(sendTime) && t.ProductCodeId.Contains(code));
            return queryStoreStockContent.Count();
        }
        /// <summary>
        /// 预配套
        /// </summary>
        /// <param name="bomAnalyseContentDtos"></param>
        /// <returns></returns>
        public async Task<ResultMessage> ExecutePreSuite(List<BomAnalyseContentDto> bomAnalyseContentDtos)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var errormessage = "";
                if (bomAnalyseContentDtos != null)
                {
                    //根据预配套状态属性 进行预配套
                    foreach (BomAnalyseContentDto bomAnalyseContentDto in bomAnalyseContentDtos)
                    {
                        if (bomAnalyseContentDto.PreSuiteStatusName == "仓库无物料" || bomAnalyseContentDto.UsableQuantityStock == 0)
                        {
                            errormessage += "物料图号：" + bomAnalyseContentDto.MaterialName + " 名称：" + bomAnalyseContentDto.MaterialName + " 规格：" + bomAnalyseContentDto.Module;
                            continue;
                        }
                        await CalculationCom(bomAnalyseContentDto, (int)BomAnalyseEnum.CompletePatterns.自动配套);
                        _iOperationHistoryAppService.InsertOperationLogNew(bomAnalyseContentDto.MaterialsContentId, BusinessTypes.设计BOM预配套分析, OperationTypes.预配套, "预配套");
                    }
                }
                if (errormessage != "")
                {
                    resultMessage.Message = errormessage + "可用库存数量为0";
                }
                else 
                {
                    resultMessage.Message = "操作成功";
                }
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 计算配套数量
        /// </summary>
        /// <param name="bomAnalyseContentDto"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        private async Task CalculationCom(BomAnalyseContentDto bomAnalyseContentDto, int pattern)
        {
            //根据型号发次 查出 仓库细表的所有数据 里面包含各个工步的 预配套物料信息 因 仓库的物料可以用应用到所有发次下 && DateTime.Parse(t.ExpirationDate) > DateTime.Now
            var storeStocksContent =
                                     (from queryStoreStocks in _storeStockpository.GetAll()
                                     join queryStoreStockContents in _storeStockContentRepository.GetAll().Where(t => t.SendTimeId.Contains(bomAnalyseContentDto.SendTimeId.ToString()) && t.ProductCodeId.Contains(bomAnalyseContentDto.ModuleId.ToString()) && t.Batch == "01" && t.IsPreSuit == IsSuits.否 && t.BomAnalysecontentId == null && (DateTime.Parse(t.ExpirationDate)) > DateTime.Now) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                     where queryStoreStockContents.StoreId == bomAnalyseContentDto.StoreId
                                     select queryStoreStockContents).Union(from queryStoreStocks in _storeStockpository.GetAll()
                                                                           join queryStoreStockContents in _storeStockContentRepository.GetAll().Where(t => t.ProductCode.Contains(bomAnalyseContentDto.HJXH + "系列") && t.Batch == "01" && t.IsPreSuit == IsSuits.否 && t.BomAnalysecontentId == null && (DateTime.Parse(t.ExpirationDate)) > DateTime.Now) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                           where queryStoreStockContents.StoreId == bomAnalyseContentDto.StoreId
                                                                           select queryStoreStockContents).ToList();
            if (storeStocksContent == null || storeStocksContent.Count() == 0)
            {
                return;
            }
            int preSuiteStock = 0;
            StoreStock storeStockContents = new StoreStock();
            //根据库存信息主表id 找出主表信息 因为要更新主表信息
            try
            {
                storeStockContents = _storeStockpository.FirstOrDefaultAsync(t => t.MaterialsContentId == bomAnalyseContentDto.MaterialsContentId && t.Id == bomAnalyseContentDto.StoreStockId).Result;
                Guid guid = Guid.Empty;
                var userId = GetCurrentUser().Id; //add 11/30
                var userData = _userRepository.FirstOrDefaultAsync(t => t.Id == userId).Result;
                //string idJoin = "";
                List<StoreStockContentDto> storeStockContentDtos = new List<StoreStockContentDto>();
                if (bomAnalyseContentDto.storeStockContentDtoList != null && bomAnalyseContentDto.storeStockContentDtoList.Count > 0)
                {
                    //找出集合中没有预配套的数量
                    storeStockContentDtos = bomAnalyseContentDto.storeStockContentDtoList.Where(t => t.IsPreSuit == (int)IsSuits.否 && t.BomAnalysecontentId == null).ToList();
                    //dJoin = string.Join(",", queryNoStoreStock);
                }
                List<StoreStockContent> stores = null;
                switch (bomAnalyseContentDto.PreSuiteStatus)
                {
                    //如果未配套：预配套数量为0 出库数量为0   
                    case (int)CompleteStatus.未预配套:
                        /*如果是自动配套 不存在 预配套中的情况*/
                        //根据 图号、规格 查询 库存详细表 并进行创建时间进行排序 先进先出
                        //var queryStoreStockContent = _storeStockContentRepository.GetAll().Where(t => t.Module == bomAnalyseContentDto.Module && t.ProductDrawingNo == bomAnalyseContentDto.MaterialNo).OrderBy(t=>t.CreationTime);
                        //if (queryStoreStockContent.Count() > 0 && queryStoreStockContent != null) 
                        //{
                        //可用库存数量 小于 芯级用量 说明 缺料
                        if (bomAnalyseContentDto.UsableQuantityStock < bomAnalyseContentDto.BomDosageTotalAmount)
                        {
                            //缺料数量计算
                            storeStockContents.StarvingStock = bomAnalyseContentDto.BomDosageTotalAmount - bomAnalyseContentDto.UsableQuantityStock;
                            //预配套数量 可用数量更新到预配套数量中
                            preSuiteStock = bomAnalyseContentDto.UsableQuantityStock;
                            storeStockContents.PreSuiteStock = preSuiteStock;
                            if ((int)CompletePatterns.自动配套 == pattern)
                            {
                                //自由库存数量  自由库存数量  -可用库存数量
                                //如果可用数量为0 自由数量值不变 否则清零
                                if (bomAnalyseContentDto.UsableQuantityStock == 0)
                                {
                                    storeStockContents.FreeQuantityStock = bomAnalyseContentDto.FreeQuantityStock;
                                }
                                else
                                {
                                    storeStockContents.FreeQuantityStock = 0;
                                }
                                //可用库存数量 ：为0  
                                storeStockContents.UsableQuantityStock = 0;
                            }
                            else if ((int)CompletePatterns.人工配套 == pattern)
                            {
                                //可用库存数量 ：为0 
                                storeStockContents.UsableQuantityStock = bomAnalyseContentDto.UsableQuantityStock - bomAnalyseContentDto.storeStockContentDtoList.Count();
                            }
                            //预配套状态
                            storeStockContents.PreSuiteStatus = (int)CompleteStatus.缺料;
                        }
                        //可用数量 大于等于 芯级用量  不缺料 
                        else if (bomAnalyseContentDto.UsableQuantityStock >= bomAnalyseContentDto.BomDosageTotalAmount)
                        {
                            if ((int)CompletePatterns.自动配套 == pattern)
                            {
                                //缺料为0
                                storeStockContents.StarvingStock = 0;
                                //预配套数量  =芯级用量
                                storeStockContents.PreSuiteStock = bomAnalyseContentDto.BomDosageTotalAmount;
                                //可用库存数量：可用库存数量 - 芯级用量
                                storeStockContents.UsableQuantityStock = bomAnalyseContentDto.UsableQuantityStock - bomAnalyseContentDto.BomDosageTotalAmount;
                                //自由库存数量：自由库存数量  - 可用库存数量
                                storeStockContents.FreeQuantityStock = bomAnalyseContentDto.FreeQuantityStock - storeStockContents.PreSuiteStock;
                                //预配套状态
                                storeStockContents.PreSuiteStatus = (int)CompleteStatus.已预配套;
                            }
                            else if ((int)CompletePatterns.人工配套 == pattern)
                            {
                                //缺料为0
                                storeStockContents.StarvingStock = 0;
                                //预配套数量  =预配套数量 + 人工配套数量
                                storeStockContents.PreSuiteStock = bomAnalyseContentDto.PreSuiteStock + bomAnalyseContentDto.storeStockContentDtoList.Count();
                                // //可用库存数量：可用库存数量 - 人工配套数量
                                storeStockContents.UsableQuantityStock = bomAnalyseContentDto.UsableQuantityStock - bomAnalyseContentDto.storeStockContentDtoList.Count();
                                //自由库存数量：自由库存数量  - 人工配套数量
                                storeStockContents.FreeQuantityStock = bomAnalyseContentDto.FreeQuantityStock - bomAnalyseContentDto.storeStockContentDtoList.Count();
                                if (storeStockContents.PreSuiteStock < bomAnalyseContentDto.BomDosageTotalAmount)
                                {
                                    //预配套状态
                                    storeStockContents.PreSuiteStatus = (int)CompleteStatus.预配套中;
                                }
                            }
                        }
                        storeStockContents.PreSuiteTime = DateTime.Now;
                        storeStockContents.PreSuiteName = userData.Surname + userData.Name;
                        storeStockContents.CollectBomManagerId = bomAnalyseContentDto.CollectBomManagerId;
                        await _storeStockpository.InsertOrUpdateAsync(storeStockContents);
                        //更新库存子表相关字段
                        // 怎么找出可用的库存子表数据？
                        //if (storeStockContents != null)
                        //{
                        //循环更新子表数据   /* 撤销配套  /*具体现在有两种模式 1：把原有数据放在缓存 2：每次撤销根据 BomAnalyseContentDto表里的数据进行 查询子表更新*/*/&& bomAnalyseContentDto.ProductNumber.Contains(t.ProductNumber)

                        if ((int)CompletePatterns.自动配套 == pattern)
                        {
                            if (bomAnalyseContentDto.MaterialTypeName == "零件")
                            {
                                stores = storeStocksContent.Where(t => t.MaterialsContentId == bomAnalyseContentDto.MaterialsContentId).OrderBy(t => t.SendTimeLength).ThenBy(t => t.CreationTime).Take(bomAnalyseContentDto.BomDosageTotalAmount).ToList();
                            }
                            else if (bomAnalyseContentDto.MaterialTypeName == "标准件")
                            {
                                //var collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(bomAnalyseContentDto.XJId);
                                //string years = "";
                                //var dyMaterils = collectBomMaterialsContentDtos.FirstOrDefault(t => t.MerialsId == bomAnalyseContentDto.MaterialsContentId);
                                //if (dyMaterils != null)
                                //{
                                //    years = dyMaterils.YearsNo;
                                //}
                                //分割materno (格式为图号-年代号)
                                //if (bomAnalyseContentDto.MaterialNo.Split('-').Count()>1) 
                                //{
                                //    //取第二个  如果数据不规范得校验 是否是数字格式 这个后期看情况
                                //    years = bomAnalyseContentDto.MaterialNo.Split('-')[1];&& bomAnalyseContentDto.ProductNumber.Contains(t.ProductNumber)
                                //}
                                if (bomAnalyseContentDto.YearsNo == "")
                                {
                                    bomAnalyseContentDto.YearsNo = "2099";
                                }
                                int u = 0;
                                stores = storeStocksContent.Where(t => t.MaterialsContentId == bomAnalyseContentDto.MaterialsContentId).OrderBy(t => t.SendTimeLength)
                                    .ThenBy(ee =>
                                    {
                                        u = Array.IndexOf(new string[]
                                        { bomAnalyseContentDto.YearsNo }, ee.Years);
                                        if (u != -1) { return u; }
                                        else { return int.MaxValue; }
                                    }).ThenBy(t => t.CreationTime).Take(bomAnalyseContentDto.BomDosageTotalAmount).ToList();
                            }
                            await UpdateStoreStockContent(stores.ToList(), guid, bomAnalyseContentDto, userData);
                        }
                        else
                        {
                            var storeSId = bomAnalyseContentDto.storeStockContentDtoList.Select(t => t.Id);
                            var bomAnalyseMatingContentDtoNew = _storeStockContentRepository.GetAll().Where(t => storeSId.Contains(t.Id));
                            bomAnalyseMatingContentDtoNew.OrderBy(t => t.SendTimeLength).ThenBy(t => t.CreationTime).ToList();
                            await UpdateStoreStockContent(bomAnalyseMatingContentDtoNew.ToList(), guid, bomAnalyseContentDto, userData);
                        }
                        break;
                    case (int)CompleteStatus.预配套中:
                        /*针对于手工配套后 没配完的情况*/
                        #region   插入预配套表
                        //给数量赋值

                        if ((int)CompletePatterns.自动配套 == pattern)
                        {
                            //缺料数量
                            storeStockContents.StarvingStock = 0;
                            //预配套数量
                            storeStockContents.PreSuiteStock = bomAnalyseContentDto.BomDosageTotalAmount;
                            //可用库存数量 ：可用库存数量 - 芯及用量
                            storeStockContents.UsableQuantityStock = bomAnalyseContentDto.UsableQuantityStock - storeStockContents.PreSuiteStock;
                            //自由库存数量  自由库存数量  -可用库存数量
                            storeStockContents.FreeQuantityStock = bomAnalyseContentDto.FreeQuantityStock - storeStockContents.UsableQuantityStock;
                            //预配套状态
                            storeStockContents.PreSuiteStatus = (int)CompleteStatus.已预配套;
                        }
                        else if ((int)CompletePatterns.人工配套 == pattern)
                        {
                            //缺料数量
                            storeStockContents.StarvingStock = 0;
                            //预配套数量 =人工配套数量(因为人工配套数量是选择的总数量)
                            storeStockContents.PreSuiteStock = bomAnalyseContentDto.storeStockContentDtoList.Count();
                            //可用库存数量 ：可用库存数量 - 人工配套数量
                            storeStockContents.UsableQuantityStock = storeStockContents.TotalQuantity - bomAnalyseContentDto.storeStockContentDtoList.Count();
                            //自由库存数量  总数量  -人工配套数量
                            storeStockContents.FreeQuantityStock = storeStockContents.TotalQuantity - bomAnalyseContentDto.storeStockContentDtoList.Count();
                            if (storeStockContents.PreSuiteStock == bomAnalyseContentDto.BomDosageTotalAmount)
                            {
                                storeStockContents.PreSuiteStatus = (int)CompleteStatus.已预配套;
                            }
                            else if (storeStockContents.PreSuiteStock < bomAnalyseContentDto.BomDosageTotalAmount)
                            {
                                storeStockContents.PreSuiteStatus = (int)CompleteStatus.预配套中;
                            }
                        }
                        #endregion
                        //根据库存主表id 查询 数据是否存在是否存在


                        //如果存在 更新 否则插入
                        if (storeStockContents != null)
                        {
                            #region 更新入库主表相关字段
                            //可用预配套数量:
                            //storeStockContents.UsableQuantityStock = 0;
                            storeStockContents.PreSuiteTime = DateTime.Now;
                            storeStockContents.PreSuiteName = userData.Surname + userData.Name;
                            storeStockContents.CollectBomManagerId = bomAnalyseContentDto.CollectBomManagerId;
                            await _storeStockpository.InsertOrUpdateAsync(storeStockContents);
                            #endregion

                            if ((int)CompletePatterns.自动配套 == pattern)
                            {
                                if (bomAnalyseContentDto.MaterialTypeName == "零件")
                                {
                                    //&& bomAnalyseContentDto.ProductNumber.Contains(t.ProductNumber)
                                    stores = storeStocksContent.Where(t => t.MaterialsContentId == bomAnalyseContentDto.MaterialsContentId).OrderBy(t => t.SendTimeLength).ThenBy(t => t.CreationTime).Take(bomAnalyseContentDto.BomDosageTotalAmount - bomAnalyseContentDto.PreSuiteStock).ToList();
                                }
                                else if (bomAnalyseContentDto.MaterialTypeName == "标准件")
                                {
                                    //string years = "";
                                    ////分割materno (格式为图号-年代号)
                                    //var collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(bomAnalyseContentDto.XJId);
                                    //var dyMaterils = collectBomMaterialsContentDtos.FirstOrDefault(t => t.MerialsId == bomAnalyseContentDto.MaterialsContentId);
                                    //if (dyMaterils != null)
                                    //{
                                    //    years = dyMaterils.YearsNo;
                                    //}
                                    //&& bomAnalyseContentDto.ProductNumber.Contains(t.ProductNumber)
                                    if (bomAnalyseContentDto.YearsNo == "")
                                    {
                                        bomAnalyseContentDto.YearsNo = "2099";
                                    }
                                    int u = 0;
                                    stores = storeStocksContent.Where(t => t.MaterialsContentId == bomAnalyseContentDto.MaterialsContentId).OrderBy(t => t.SendTimeLength)
                                                                    .ThenBy(ee =>
                                                                    {
                                                                        u = Array.IndexOf(new string[]
                                                                        { bomAnalyseContentDto.YearsNo }, ee.Years);
                                                                        if (u != -1) { return u; }
                                                                        else { return int.MaxValue; }
                                                                    }).ThenBy(t => t.CreationTime).Take(bomAnalyseContentDto.BomDosageTotalAmount - bomAnalyseContentDto.PreSuiteStock).ToList();
                                }
                                await UpdateStoreStockContent(stores.ToList(), guid, bomAnalyseContentDto, userData);
                            }
                            else
                            {
                                var storeSId = bomAnalyseContentDto.storeStockContentDtoList.Select(t => t.Id);
                                var bomAnalyseMatingContentDtoNew = _storeStockContentRepository.GetAll().Where(t => storeSId.Contains(t.Id));
                                bomAnalyseMatingContentDtoNew.OrderBy(t => t.SendTimeLength).ThenBy(t => t.CreationTime).ToList();
                                await UpdateStoreStockContent(bomAnalyseMatingContentDtoNew.ToList(), guid, bomAnalyseContentDto, userData);
                            }
                        }
                        break;
                    case (int)CompleteStatus.缺料:
                        #region   插入预配套表
                        //给数量赋值0
                        if ((int)CompletePatterns.自动配套 == pattern)
                        {
                            //缺料数量：可用库存数量 -缺料数量 这里可能存在负数？***
                            storeStockContents.StarvingStock = bomAnalyseContentDto.UsableQuantityStock - bomAnalyseContentDto.StarvingStock;
                            //预配套数量 ：预配套数量 +可用库存数量
                            storeStockContents.PreSuiteStock = bomAnalyseContentDto.PreSuiteStock + bomAnalyseContentDto.UsableQuantityStock;
                            //可用库存数量 ：0
                            storeStockContents.UsableQuantityStock = 0;
                            //自由库存数量  自由库存数量  -可用库存数量
                            storeStockContents.FreeQuantityStock = bomAnalyseContentDto.FreeQuantityStock - bomAnalyseContentDto.UsableQuantityStock;
                        }
                        else if ((int)CompletePatterns.人工配套 == pattern)
                        {
                            //缺料数量：可用库存数量 -缺料数量 这里可能存在负数？*** (bomDesignDetailData.BomDosageTotalAmount - queryStoreStocks.PreSuiteStock) > storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) ? bomDesignDetailData.BomDosageTotalAmount - (storeStocks.Count(t => t.StoreStockId == queryStoreStocks.Id) + queryStoreStocks.PreSuiteStock) : 0,
                            // storeStockContents.StarvingStock = bomAnalyseContentDto.storeStockContentDtoList.Count() - bomAnalyseContentDto.StarvingStock;
                            storeStockContents.StarvingStock = bomAnalyseContentDto.StarvingStock;
                            if (storeStockContents.UsableQuantityStock + storeStockContents.PreSuiteStock == bomAnalyseContentDto.storeStockContentDtoList.Count())
                            {
                                storeStockContents.UsableQuantityStock = 0;
                            }
                            else
                            {
                                storeStockContents.UsableQuantityStock = bomAnalyseContentDto.UsableQuantityStock - bomAnalyseContentDto.storeStockContentDtoList.Count();
                            }
                            //预配套数量 ：预配套数量 +人工配套数量
                            storeStockContents.PreSuiteStock = bomAnalyseContentDto.storeStockContentDtoList.Count();
                            //可用库存数量 ：可用库存数量 -人工配套数量
                            //storeStockContents.UsableQuantityStock = bomAnalyseContentDto.UsableQuantityStock - bomAnalyseContentDto.storeStockContentDtoList.Count();

                            //自由库存数量  自由库存数量  -人工配套数量 ？？？？？？？？？？？？
                            storeStockContents.FreeQuantityStock = storeStockContents.StoreQuantity - bomAnalyseContentDto.storeStockContentDtoList.Count();
                        }
                        //预配套状态
                        //存在三种情况 缺料 和 已配套 配套中
                        if (bomAnalyseContentDto.StarvingStock != 0)
                        {
                            storeStockContents.PreSuiteStatus = (int)CompleteStatus.缺料;
                        }
                        //可用库存数量<缺料数量
                        else if (storeStockContents.PreSuiteStock >= bomAnalyseContentDto.BomDosageTotalAmount)
                        {
                            storeStockContents.PreSuiteStatus = (int)CompleteStatus.已预配套;
                        }
                        //芯级用量 - 预配套数量 <=可用库存数量
                        else if (bomAnalyseContentDto.BomDosageTotalAmount - bomAnalyseContentDto.PreSuiteStock <= bomAnalyseContentDto.UsableQuantityStock)
                        {
                            storeStockContents.PreSuiteStatus = (int)CompleteStatus.预配套中;
                        }
                        storeStockContents.PreSuiteTime = DateTime.Now;
                        storeStockContents.PreSuiteName = userData.Surname + userData.Name;
                        storeStockContents.CollectBomManagerId = bomAnalyseContentDto.CollectBomManagerId;
                        await _storeStockpository.InsertOrUpdateAsync(storeStockContents);
                        //var bomAnalyseStarvingContentDtoNew = ObjectMapper.Map<BomAnalyseContent>(bomAnalyseContentDto);
                        //int bomAnalyseStarvingContent = _bomAnalyseContentRepository.Count(t => t.MaterialsContentId == bomAnalyseContentDto.MaterialsContentId);
                        //if (bomAnalyseStarvingContent > 0)
                        //{
                        //guid = _bomAnalyseContentRepository.InsertOrUpdateAndGetId(bomAnalyseStarvingContentDtoNew);
                        //   }
                        //else
                        //{
                        //guid = _bomAnalyseContentRepository.InsertOrUpdateAndGetId(bomAnalyseStarvingContentDtoNew);
                        // }
                        //根据库存主表id 查出 子表的数据是否有适用的


                        if ((int)CompletePatterns.自动配套 == pattern)
                        {

                            if (bomAnalyseContentDto.MaterialTypeName == "零件")
                            {
                                stores = storeStocksContent.Where(t => t.MaterialsContentId == bomAnalyseContentDto.MaterialsContentId).OrderBy(t => t.SendTimeLength).ThenBy(t => t.CreationTime).Take(bomAnalyseContentDto.UsableQuantityStock).ToList();
                            }
                            else if (bomAnalyseContentDto.MaterialTypeName == "标准件")
                            {
                                //string yearss = "";
                                ////分割materno (格式为图号-年代号)
                                //var collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(bomAnalyseContentDto.XJId);
                                //var dyMaterils = collectBomMaterialsContentDtos.FirstOrDefault(t => t.MerialsId == bomAnalyseContentDto.MaterialsContentId);
                                //if (dyMaterils != null)
                                //{
                                //    yearss = dyMaterils.YearsNo;
                                //}
                                //string[] storesSplit = yearss.Split(',');
                                //if (storesSplit.Length > 0) 
                                //{
                                //    for (int i = 0; i < storesSplit.Length; i++) 
                                //    {
                                //        stores = storeStocksContent.Where(t => t.MaterialsContentId == bomAnalyseContentDto.MaterialsContentId).OrderBy(t => t.SendTimeLength).ThenByDescending(t =>t.Years== storesSplit[i]).ToList();
                                //    }
                                //}
                                if (bomAnalyseContentDto.YearsNo == "")
                                {
                                    bomAnalyseContentDto.YearsNo = "2099";
                                }
                                int u = 0;
                                stores = storeStocksContent.Where(t => t.MaterialsContentId == bomAnalyseContentDto.MaterialsContentId).OrderBy(t => t.SendTimeLength)
                                                                .ThenBy(ee =>
                                                                {
                                                                    u = Array.IndexOf(new string[]
                                                                    { bomAnalyseContentDto.YearsNo }, ee.Years);
                                                                    if (u != -1) { return u; }
                                                                    else { return int.MaxValue; }
                                                                }).ThenBy(t => t.CreationTime).Take(bomAnalyseContentDto.UsableQuantityStock).ToList();
                            }
                            await UpdateStoreStockContent(stores.ToList(), guid, bomAnalyseContentDto, userData);
                        }
                        else
                        {
                            //var bomAnalyseMatingContentDtoNew = ObjectMapper.Map<List<StoreStockContent>>(bomAnalyseContentDto.storeStockContentDtoList);
                            var storeSId = bomAnalyseContentDto.storeStockContentDtoList.Select(t => t.Id);
                            var bomAnalyseMatingContentDtoNew = _storeStockContentRepository.GetAll().Where(t => storeSId.Contains(t.Id));
                            bomAnalyseMatingContentDtoNew.OrderBy(t => t.SendTimeLength).ThenBy(t => t.CreationTime).ToList();
                            await UpdateStoreStockContent(bomAnalyseMatingContentDtoNew.ToList(), guid, bomAnalyseContentDto, userData);
                        }
                        #endregion
                        break;
                    default:
                        break;
                }
            }
            catch
            {


            }

        }
        /// <summary>
        /// 取消预配套 只针对于已经配套完成的
        /// </summary>
        /// <param name="bomAnalyseContentDtos"></param>
        public async Task<ResultMessage> CancelPreSuite(List<BomAnalyseContentDto> bomAnalyseContentDtos)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                if (bomAnalyseContentDtos != null)
                {
                    //循环选中物料 
                    foreach (BomAnalyseContentDto bomAnalyseContentDto in bomAnalyseContentDtos)
                    {
                        if (bomAnalyseContentDto.PreSuiteStatus == (int)CompleteStatus.未预配套 || bomAnalyseContentDto.PreSuiteStatusName == "仓库无物料")
                        {
                            continue;
                        }
                        //先查出库存主表数据
                        var storeStockContentList = _storeStockpository.GetAll().Where(t => t.Id == bomAnalyseContentDto.StoreStockId);
                        if (storeStockContentList != null)
                        {
                            //storeStockContentList.ToList()[0].MatingStatus != 1 &&
                            //if (bomAnalyseContentDto.SuiteStock != 0)
                            //{
                            //    throw new UserFriendlyException("物料代码:" + storeStockContentList.ToList()[0].ProductDrawingNo + "已配套,请先解配套");
                            //}
                            //去除库存子表的 预配套状态 和 占用id 更新 条件 ：
                            var bomAnalyseContent = (from storeStock in storeStockContentList
                                                     join storeStockContent in _storeStockContentRepository.GetAll().Where(t => t.BomAnalysecontentId == bomAnalyseContentDto.CollectBomManagerId) on storeStock.Id equals storeStockContent.StoreStockId
                                                     // where storeStock.ProductNumber.Contains(storeStockContent.ProductNumber)
                                                     select storeStockContent).OrderBy(t => t.CreationTime);
                            if (bomAnalyseContent.Count() == 0)
                            {
                                return null;
                            }
                            var queryIsSuitCount = bomAnalyseContent.Count(t => t.IsSuit == IsSuits.是 && t.LoadDetailsId != null);
                            if (queryIsSuitCount > 0)
                            {
                                throw new UserFriendlyException("存在配套数据,请先解配套");
                            }
                            foreach (StoreStockContent storeStockContent in bomAnalyseContent)
                            {
                                storeStockContent.BomAnalysecontentId = null;
                                storeStockContent.IsPreSuit = IsSuits.否;
                                storeStockContent.DesignatedModule = null;
                                storeStockContent.DesignatedSendTime = null;
                                storeStockContent.DesignatedXJCode = null;
                                storeStockContent.DesignatedXJ = null;
                                storeStockContent.PreSuiteName = null;
                                storeStockContent.PreSuiteTime = null;
                                await _storeStockContentRepository.UpdateAsync(storeStockContent);
                            }
                            //更新库存主表的数量 
                            //库存主表的 数量 需要更改哪些？ 1：可用预配套数量 2：预配套数量 3：自由库存数量 
                            foreach (StoreStock store in storeStockContentList)
                            {
                                store.UsableQuantityStock += store.PreSuiteStock;
                                store.FreeQuantityStock += store.PreSuiteStock;
                                store.PreSuiteStock = 0;
                                store.PreSuiteStatus = (int)CompleteStatus.未预配套;
                                store.PreSuiteTime = null;
                                store.PreSuiteName = null;
                                store.StarvingStock = 0;
                                await _storeStockpository.UpdateAsync(store);
                            }
                        }
                        // 更新预配套表的数量信息 ： 1：可用库存数量 
                        //bomAnalyseContentDto.UsableQuantityStock = bomAnalyseContent.Count();
                        //var bomAnalyseMatingContentDtoNew = ObjectMapper.Map<BomAnalyseContent>(bomAnalyseContentDto);
                        //await _bomAnalyseContentRepository.UpdateAsync(bomAnalyseMatingContentDtoNew);
                        // bomAnalyseContentDto.StarvingStock = 0;
                        _iOperationHistoryAppService.InsertOperationLogNew(bomAnalyseContentDto.MaterialsContentId, BusinessTypes.设计BOM预配套分析, OperationTypes.预配套, "取消预配套");
                    }
                }
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 查询人工预配套信息
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public async Task<List<StoreStockContentDto>> GetExecutePreSuitePerson(Guid guid, Guid collid)
        {
            var userData = _userRepository.GetAll().ToList();
            var storeStockContent = _storeStockpository.FirstOrDefaultAsync(t => t.Id == guid).Result;
            var coll = _collectBomManagerRepository.FirstOrDefault(s => s.Id == collid);
            string module = "";
            module = coll?.Module;
            //Guid modulexlId = _sysCodeRepository.FirstOrDefaultAsync(t => t.Description == module + "系列").Result.Id;
            if (storeStockContent == null)
            {
                throw new UserFriendlyException("仓库没有该物料");
            }
            //查出库存子表的相关数据
            var querybomAnalyseContent = from queryStoreStockContent in _storeStockContentRepository.GetAll().Where(t => (t.BomAnalysecontentId == null && t.IsPreSuit == IsSuits.否 && t.StoreStockId == storeStockContent.Id && (t.MaterialsProperty == StoreManagement.MaterialsPropertys.正常品 || t.MaterialsProperty == StoreManagement.MaterialsPropertys.返修正常品)) || (t.BomAnalysecontentId
                                         != null && t.IsPreSuit == IsSuits.是 && t.StoreStockId == storeStockContent.Id && t.BomAnalysecontentId == collid && (t.MaterialsProperty == StoreManagement.MaterialsPropertys.正常品 || t.MaterialsProperty == StoreManagement.MaterialsPropertys.返修正常品)))
                                         join storePutContent in _storePutContentRepository.GetAll() on queryStoreStockContent.StorePutContentId equals storePutContent.Id
                                         join materialsContent in _materialsContentRepository.GetAll() on queryStoreStockContent.MaterialsContentId equals materialsContent.Id
                                         join queryNode in _materialsNoderepository.GetAll() on materialsContent.MaterialsNodeId equals queryNode.Id
                                         join queryNodeChild in _materialsNoderepository.GetAll() on materialsContent.MaterialCategoryId equals queryNodeChild.Id
                                         join users in userData on storePutContent.StorePutPeopleId equals users.Id into Joinmu
                                         from mu in Joinmu.DefaultIfEmpty()
                                         join affirmuser in userData on storePutContent.IdentifyingPeopleId equals affirmuser.Id into JoinmuAff
                                         from muff in JoinmuAff.DefaultIfEmpty()
                                         where (queryStoreStockContent.ProductCodeId.Contains(coll.ModuleId.ToString()) && queryStoreStockContent.SendTimeId.Contains(coll.SendTimeId.ToString()))
                                         || (queryStoreStockContent.ProductCode.Contains(module + "系列"))
                                         select new StoreStockContentDto
                                         {
                                             CreationTime = queryStoreStockContent.CreationTime, //add 12/1
                                             BomAnalysecontentId = queryStoreStockContent.BomAnalysecontentId,
                                             MaterialsContentId = queryStoreStockContent.MaterialsContentId,
                                             ProductCode = queryStoreStockContent.ProductCode,
                                             ProductCodeId = queryStoreStockContent.ProductCodeId,
                                             StoreId = queryStoreStockContent.StoreId,
                                             StoreStockId = queryStoreStockContent.StoreStockId,
                                             Id = queryStoreStockContent.Id,
                                             StorePutContentId = storePutContent.Id,
                                             //储位
                                             BinLocation = queryStoreStockContent.BinLocation,
                                             //仓库名称
                                             StroeName = queryStoreStockContent.StroeName,
                                             //产品图号
                                             ProductDrawingNo = queryStoreStockContent.ProductDrawingNo,
                                             //规格型号
                                             Module = queryStoreStockContent.Module,
                                             //产品名称
                                             ProductName = queryStoreStockContent.ProductName,
                                             //物料细类
                                             MaterialCategory = queryNodeChild.MaterialTypeName,
                                             //物料类别
                                             MaterialsNode = queryNode.MaterialTypeName,
                                             MaterialsPropertyName = queryStoreStockContent.OutboundState == OutboundStates.在库 ? "库存" : queryStoreStockContent.OutboundState == OutboundStates.出库 ? "已出库" : "未领料",
                                             MaterialsProperty = (int)queryStoreStockContent.OutboundState,
                                             //合格整号
                                             QualifiedNumber = queryStoreStockContent.QualifiedNumber,
                                             //放行单号
                                             ReleaseOrder = queryStoreStockContent.ReleaseOrder,
                                             //质控卡号
                                             QCCardNo = storePutContent.QCCardNo,
                                             //发次
                                             SendTime = queryStoreStockContent.SendTime,
                                             SendTimeId = queryStoreStockContent.SendTimeId,
                                             //批次
                                             Batch = queryStoreStockContent.Batch,
                                             //合格证任务号
                                             QualifiedTaskNumber = storePutContent.QualifiedTaskNumber,
                                             //装配任务号
                                             AssemblyTaskNumber = storePutContent.AssemblyTaskNumber,
                                             //数量
                                             Quantity = 1,
                                             //产品编号
                                             ProductNumber = queryStoreStockContent.ProductNumber,
                                             //有效期止
                                             ExpirationDate = queryStoreStockContent.ExpirationDate == "2099-01-01T00:00:00.000Z" ? null : queryStoreStockContent.ExpirationDate,
                                             //入库人
                                             StorePutPeople = mu.Surname + mu.Name,
                                             //入库时间
                                             StorePutTime = storePutContent.StorePutTime,
                                             //
                                             Remark = storePutContent.Remark,
                                             //确认时间
                                             IdentifyingTime = storePutContent.IdentifyingTime,
                                             //确认人
                                             IdentifyingPeople = mu.Surname + mu.Name,
                                             SuitStuts = queryStoreStockContent.IsSuit == (IsSuits)1 ? "配套" : "",
                                             IsPreSuit = (int)queryStoreStockContent.IsPreSuit,
                                             //特殊记载
                                             SpecialRecords = storePutContent.SpecialRecords,
                                             //预配套人
                                             PreSuiteName = queryStoreStockContent.PreSuiteName,
                                             //预配套时间
                                             PreSuiteTime = queryStoreStockContent.PreSuiteTime,
                                             //配套人
                                             CompletePeople = queryStoreStockContent.CompletePeople,
                                             //配套时间
                                             CompleteTime = queryStoreStockContent.CompleteTime,
                                             Years = queryStoreStockContent.Years
                                         };
            if (querybomAnalyseContent != null && querybomAnalyseContent.Count() > 0)
            {
                return querybomAnalyseContent.OrderBy(t => t.CreationTime).ToList(); //add 12/1
            }
            return new List<StoreStockContentDto>();
        }
        /// <summary>
        /// 人工预配套 人工取消预配套
        /// </summary>
        /// <param name="bomAnalyseContentDto"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        public async Task<ResultMessage> ExecutePreSuitePerson(BomAnalyseContentDto bomAnalyseContentDto)
        {
            ResultMessage resultMessage = new ResultMessage();
            //根据集合 
            if (bomAnalyseContentDto.storeStockContentDtoList != null)
            {
                //if (bomAnalyseContentDto.storeStockContentDtoList.Count > 0)
                //{
                //先查出当前库存主表数据
                var queryStoreStockList = _storeStockpository.FirstOrDefaultAsync(t => t.Id == bomAnalyseContentDto.StoreStockId).Result;
                //找出库存信息子表数据
                var queryStoreStockContentList = _storeStockContentRepository.GetAll().Where(t => t.StoreStockId == bomAnalyseContentDto.StoreStockId);
                //找出库存信息已预配套的条数
                var queryStoreStockContentCount = _storeStockContentRepository.Count(t => t.StoreStockId == bomAnalyseContentDto.StoreStockId && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.BomAnalysecontentId == bomAnalyseContentDto.CollectBomManagerId);
                var queryStoreStockContent = _storeStockContentRepository.GetAll().Where(t => t.StoreStockId == bomAnalyseContentDto.StoreStockId && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.BomAnalysecontentId == bomAnalyseContentDto.CollectBomManagerId);
                //找出集合中没有预配套的数量
                var queryNoStoreStock = bomAnalyseContentDto.storeStockContentDtoList.Where(t => t.IsPreSuit == (int)IsSuits.否 && t.BomAnalysecontentId == null);
                //如果配套数量大于芯级用量 提示变更数量
                if (bomAnalyseContentDto.BomDosageTotalAmount < bomAnalyseContentDto.storeStockContentDtoList.Count())
                {
                    resultMessage.Message = "超出芯级用量，数量请先进行变更";
                    resultMessage.code = 1;
                    return resultMessage;

                }
                //如果 已预配套的数量 大于 选择的数量 = 解配套  否则是预配套   已预配套的数量 等于 选择的数量  =预配套||解配套
                if (queryStoreStockContentCount >= bomAnalyseContentDto.storeStockContentDtoList.Count())
                {
                    List<StoreStockContent> stockContent = new List<StoreStockContent>();
                    string joinId = "";
                    //如果list 为0说明是最后一条 joinId ="";
                    //if (bomAnalyseContentDto.storeStockContentDtoList.Count != 0)
                    //{
                    if (bomAnalyseContentDto.storeStockContentDtoList.Count == 0)
                    {
                        //&& bomAnalyseContentDto.ProductNumber.Contains(t.ProductNumber)
                        var queryStoreStockContentResult = _storeStockContentRepository.GetAll().Where(t => t.StoreStockId == bomAnalyseContentDto.StoreStockId && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.BomAnalysecontentId == bomAnalyseContentDto.CollectBomManagerId);
                        foreach (StoreStockContent storeStockContent in queryStoreStockContentResult)
                        {
                            storeStockContent.IsPreSuit = IsSuits.否;
                            storeStockContent.BomAnalysecontentId = null;
                            storeStockContent.DesignatedModule = null;
                            storeStockContent.DesignatedSendTime = null;
                            storeStockContent.DesignatedXJCode = null;
                            storeStockContent.DesignatedXJ = null;
                            storeStockContent.PreSuiteName = null;
                            storeStockContent.PreSuiteTime = null;
                            stockContent.Add(storeStockContent);

                        }
                        queryStoreStockList.CollectBomManagerId = null;
                        //queryStoreStockList.PreSuiteTime = null;
                        //queryStoreStockList.PreSuiteName = null;
                        //await _storeStockpository.UpdateAsync(queryStoreStockList);
                    }
                    else
                    {
                        joinId = string.Join(",", bomAnalyseContentDto.storeStockContentDtoList.Select(t => t.Id));
                        foreach (StoreStockContent storeStockContent in queryStoreStockContent.ToList())
                        {

                            if (!joinId.Contains(storeStockContent.Id.ToString()))
                            {
                                if (storeStockContent.IsSuit == IsSuits.是 && storeStockContent.LoadDetailsId != null)
                                {
                                    resultMessage.Message = "名称：" + storeStockContent.ProductName + ",图号" + storeStockContent.ProductDrawingNo + "-" + storeStockContent.Module + ",产品编号" + storeStockContent.ProductNumber + ":该物料已配套请先解配套";
                                    resultMessage.code = 1;
                                    return resultMessage;
                                }
                                storeStockContent.IsPreSuit = IsSuits.否;
                                storeStockContent.BomAnalysecontentId = null;
                                storeStockContent.DesignatedModule = null;
                                storeStockContent.DesignatedSendTime = null;
                                storeStockContent.DesignatedXJCode = null;
                                storeStockContent.DesignatedXJ = null;
                                storeStockContent.PreSuiteName = null;
                                storeStockContent.PreSuiteTime = null;
                                stockContent.Add(storeStockContent);
                            }
                        }
                    }
                    if (stockContent.Count > 0)
                    {
                        foreach (StoreStockContent content in stockContent)
                        {
                            await _storeStockContentRepository.UpdateAsync(content);
                        }
                    }
                    //更新子表数据

                    //queryStoreStockContentList.ToList().ForEach(t =>
                    //{
                    //    t.IsPreSuit = IsSuits.否;
                    //    t.BomAnalysecontentId = null;
                    //    t.DesignatedModule = null;
                    //    t.DesignatedSendTime = null;
                    //    if (!joinId.Contains(t.Id.ToString())) 
                    //    {
                    //        _storeStockContentRepository.UpdateAsync(t);
                    //    }
                    //});
                    //更新库存主表信息
                    queryStoreStockList.PreSuiteTime = null;
                    queryStoreStockList.PreSuiteName = null;
                    //queryStoreStockList.CollectBomManagerId = null;
                    queryStoreStockList.UsableQuantityStock += bomAnalyseContentDto.storeStockContentDtoList.Count == 0 ? bomAnalyseContentDto.storeStockContentDtoList.Count + 1 : queryStoreStockList.PreSuiteStock - bomAnalyseContentDto.storeStockContentDtoList.Count;
                    queryStoreStockList.PreSuiteStock = bomAnalyseContentDto.storeStockContentDtoList.Count;
                    queryStoreStockList.FreeQuantityStock = queryStoreStockContentList.Count() - bomAnalyseContentDto.storeStockContentDtoList.Count;
                    if (bomAnalyseContentDto.StarvingStock != 0)
                    {
                        queryStoreStockList.PreSuiteStatus = (int)CompleteStatus.缺料;
                    }
                    else
                    {
                        if (bomAnalyseContentDto.BomDosageTotalAmount - queryStoreStockList.PreSuiteStock >= queryStoreStockList.UsableQuantityStock && queryStoreStockList.PreSuiteStock != 0)
                        {
                            queryStoreStockList.PreSuiteStatus = (int)CompleteStatus.预配套中;
                        }
                        else if (bomAnalyseContentDto.BomDosageTotalAmount - queryStoreStockList.PreSuiteStock == bomAnalyseContentDto.BomDosageTotalAmount && queryStoreStockList.PreSuiteStock == 0)
                        {
                            queryStoreStockList.PreSuiteStatus = (int)CompleteStatus.未预配套;
                        }
                    }
                    var listNew = ObjectMapper.Map<StoreStock>(queryStoreStockList);
                    await _storeStockpository.UpdateAsync(listNew);
                    _iOperationHistoryAppService.InsertOperationLogNew(bomAnalyseContentDto.MaterialsContentId, BusinessTypes.设计BOM预配套分析, OperationTypes.人工预配套, "人工取消预配套");
                }
                else
                {
                    if (bomAnalyseContentDto.UsableQuantityStock == 0)
                    {
                        resultMessage.Message = "可用数量为0不能进行预配套(型号发次等信息不可用)";
                        resultMessage.code = 1;
                        return resultMessage;
                    }
                    await CalculationCom(bomAnalyseContentDto, (int)BomAnalyseEnum.CompletePatterns.人工配套);
                    _iOperationHistoryAppService.InsertOperationLogNew(bomAnalyseContentDto.MaterialsContentId, BusinessTypes.设计BOM预配套分析, OperationTypes.人工预配套, "人工预配套");
                }
                //  }
            }
            return resultMessage;
        }
        /// <summary>
        /// 更新库存子表数据
        /// </summary>
        /// <param name="queryStoreStockContents"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        private async Task UpdateStoreStockContent(List<StoreStockContent> queryStoreStockContents, Guid guid, BomAnalyseContentDto bomAnalyseContentDto, User user)
        {
            foreach (StoreStockContent storeStockContent in queryStoreStockContents)
            {
                storeStockContent.BomAnalysecontentId = bomAnalyseContentDto.CollectBomManagerId;
                storeStockContent.IsPreSuit = IsSuits.是;//这是是枚举值
                storeStockContent.DesignatedModule = bomAnalyseContentDto.HJXH;
                storeStockContent.DesignatedSendTime = bomAnalyseContentDto.HJFC;
                storeStockContent.DesignatedXJCode = bomAnalyseContentDto.XJCode;
                storeStockContent.DesignatedXJ = bomAnalyseContentDto.XJName;
                storeStockContent.PreSuiteName = user.Surname + user.Name;
                storeStockContent.PreSuiteTime = DateTime.Now;
                await _storeStockContentRepository.UpdateAsync(storeStockContent);
            }
        }
        /// <summary>
        /// 导出主页预配套内容
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> GetBomAnalyseContentToExcel(IList<BomAnalyseContentDto> bomAnalyseContentDtos)
        {
            List<BomAnalyseContentDto> bomAnalyseContentList = new List<BomAnalyseContentDto>();
            foreach (BomAnalyseContentDto bomAnalyseContent in bomAnalyseContentDtos)
            {
                bomAnalyseContentList.Add(bomAnalyseContent);
            }
            return _bomAnalyseExportToExcel.ExportToFile(bomAnalyseContentList);
        }
        /// <summary>
        /// 导出缺料表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> GetStarvingMaterialsToExcel(IList<BomAnalyseContentDto> bomAnalyseContentDtos)
        {
            List<BomAnalyseContentDto> bomAnalyseContentList = new List<BomAnalyseContentDto>();
            foreach (BomAnalyseContentDto bomAnalyseContent in bomAnalyseContentDtos)
            {
                if (bomAnalyseContent.PreSuiteStatusName == CompleteStatus.缺料.ToString() || bomAnalyseContent.PreSuiteStatusName == "仓库无物料" || bomAnalyseContent.PreSuiteStatusName == "")
                {
                    bomAnalyseContentList.Add(bomAnalyseContent);
                }
            }
            return _bomAnalyseExportToExcel.ExportToFile(bomAnalyseContentList);
        }
        /// <summary>
        /// 查询替代料信息
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public async Task<List<StoreStockContentDto>> GetExecutePreSuiteSubstitutions(BomAnalyseSubstituteEdit input)
        {
            var userData = _userRepository.GetAll().ToList();
            //查出库存子表的相关数据
            var querybomAnalyseContent = from storeStock in _storeStockpository.GetAll()
                                         join storeStockContent in _storeStockContentRepository.GetAll()
                                         .WhereIf(!input.StroeName.IsNullOrWhiteSpace(), t => t.StoreId == input.StroeId)
                                         .WhereIf(!input.MaterialNo.IsNullOrWhiteSpace(), t => t.ProductDrawingNo == input.MaterialNo)
                                         .WhereIf(!input.MaterialName.IsNullOrWhiteSpace(), t => t.ProductName == input.MaterialTypeName)
                                         .WhereIf(!input.Module.IsNullOrWhiteSpace(), t => t.Module == input.Module)
                                         .WhereIf(!input.ReleaseOrder.IsNullOrWhiteSpace(), t => t.ReleaseOrder == input.ReleaseOrder)
                                         .WhereIf(!input.HJXHId.Equals(Guid.Empty), t => t.ProductCodeId.Contains(input.HJXHId.ToString()))
                                         .WhereIf(!input.HJFCId.Equals(Guid.Empty), t => t.SendTimeId.Contains(input.HJFCId.ToString())) on storeStock.Id equals
                                         storeStockContent.StoreStockId
                                         join storePutContent in _storePutContentRepository.GetAll() on storeStockContent.StorePutContentId equals storePutContent.Id
                                         join materialsContent in _materialsContentRepository.GetAll() on storeStockContent.MaterialsContentId equals materialsContent.Id
                                         join queryNode in _materialsNoderepository.GetAll().WhereIf(!input.MaterialTypeName.IsNullOrWhiteSpace(), t => t.MaterialTypeName == input.MaterialTypeName) on materialsContent.MaterialsNodeId equals queryNode.Id
                                         join queryNodeChild in _materialsNoderepository.GetAll() on materialsContent.MaterialCategoryId equals queryNodeChild.Id
                                         join users in userData on storePutContent.StorePutPeopleId equals users.Id into Joinmu
                                         from mu in Joinmu.DefaultIfEmpty()
                                         join affirmuser in userData on storePutContent.IdentifyingPeopleId equals affirmuser.Id into JoinmuAff
                                         from muff in JoinmuAff.DefaultIfEmpty()
                                         where storeStockContent.IsPreSuit == IsSuits.否 && storeStockContent.BomAnalysecontentId == null && storeStockContent.BomSuitContentId == null && storeStockContent.IsSuit == IsSuits.否 && storeStockContent.LoadDetailsId == null
                                         select new StoreStockContentDto
                                         {
                                             Id = storeStockContent.Id,
                                             //仓库名称
                                             StroeName = storeStockContent.StroeName,
                                             //产品图号
                                             ProductDrawingNo = storeStockContent.ProductDrawingNo,
                                             //规格型号
                                             Module = storeStockContent.Module,
                                             //产品名称
                                             ProductName = storeStockContent.ProductName,
                                             //物料细类
                                             MaterialCategory = queryNodeChild.MaterialTypeName,
                                             //物料类别
                                             MaterialsNode = queryNode.MaterialTypeName,
                                             MaterialsPropertyName = storeStockContent.OutboundState == OutboundStates.在库 ? "库存" : storeStockContent.OutboundState == OutboundStates.出库 ? "已出库" : "未领料",
                                             //合格整号
                                             QualifiedNumber = storeStockContent.QualifiedNumber,
                                             //放行单号
                                             ReleaseOrder = storeStockContent.ReleaseOrder,
                                             //质控卡号
                                             QCCardNo = storePutContent.QCCardNo,
                                             //发次
                                             SendTime = storeStockContent.SendTime,
                                             //批次
                                             Batch = storeStockContent.Batch,
                                             //合格证任务号
                                             QualifiedTaskNumber = storePutContent.QualifiedTaskNumber,
                                             //装配任务号
                                             AssemblyTaskNumber = storePutContent.AssemblyTaskNumber,
                                             //数量
                                             Quantity = storeStockContent.Quantity,
                                             //产品编号
                                             ProductNumber = storeStockContent.ProductNumber,
                                             //有效期止
                                             ExpirationDate = storeStockContent.ExpirationDate == "2099-01-01T00:00:00.000Z" ? null : storeStockContent.ExpirationDate,
                                             //入库人
                                             StorePutPeople = mu.Surname + mu.Name,
                                             //入库时间
                                             StorePutTime = storePutContent.StorePutTime,
                                             //
                                             Remark = storePutContent.Remark,
                                             //确认时间
                                             IdentifyingTime = storePutContent.IdentifyingTime,
                                             //确认人
                                             IdentifyingPeople = mu.Surname + mu.Name,
                                             SuitStuts = storeStockContent.IsSuit == (IsSuits)1 ? "配套" : "",
                                             IsPreSuit = (int)storeStockContent.IsPreSuit
                                         };
            if (querybomAnalyseContent != null && querybomAnalyseContent.Count() > 0)
            {
                return querybomAnalyseContent.ToList();
            }
            return new List<StoreStockContentDto>();
        }

        /// <summary>
        /// 取消预配套 业务外调用 
        /// </summary>
        /// <param name="storeStockContents"></param>
        /// <returns></returns>
        public async Task ExteriorCancelPreSuite(List<StoreStockContent> storeStockContents)
        {
            if (storeStockContents.Count > 0)
            {
                List<StoreStockContent> stockContent = new List<StoreStockContent>();
                //查出库存主表数据
                var storeStockContentList = _storeStockpository.FirstOrDefaultAsync(t => t.Id == storeStockContents[0].StoreStockId && t.StoreId == storeStockContents[0].StoreId).Result;
                var storeStockContentCount = _storeStockContentRepository.Count(t => t.StoreStockId == storeStockContentList.Id && t.StoreId == storeStockContentList.StoreId);
                if (storeStockContentList != null)
                {
                    //更新子表数据
                    foreach (StoreStockContent storeStockContent in storeStockContents)
                    {
                        //if (!storeStockContent.Id.ToString().Contains(joinId))
                        //{
                        storeStockContent.IsPreSuit = IsSuits.否;
                        storeStockContent.BomAnalysecontentId = null;
                        storeStockContent.PreSuiteName = null;
                        storeStockContent.PreSuiteTime = null;
                        storeStockContent.BomAnalysecontentId = null;
                        storeStockContent.PreSuiteName = null;
                        storeStockContent.PreSuiteTime = null;
                        stockContent.Add(storeStockContent);
                        //}
                    }
                    if (stockContent.Count > 0)
                    {
                        foreach (StoreStockContent content in stockContent)
                        {
                            await _storeStockContentRepository.UpdateAsync(content);
                        }
                    }
                    storeStockContentList.PreSuiteTime = null;
                    storeStockContentList.PreSuiteName = null;
                    storeStockContentList.CollectBomManagerId = null;
                    //storeStockContentList.UsableMatingQuantityStock += storeStockContents.Count == 0 ? storeStockContents.Count + 1 : storeStockContentList.SuiteStock - storeStockContents.Count;
                    storeStockContentList.UsableQuantityStock += storeStockContents.Count;
                    storeStockContentList.PreSuiteStock -= storeStockContents.Count;
                    if (storeStockContentCount > storeStockContents.Count)
                    {
                        storeStockContentList.MatingStatus = (int)CompleteStatus.预配套中;
                    }
                    else if (storeStockContentCount == storeStockContents.Count)
                    {
                        storeStockContentList.MatingStatus = (int)CompleteStatus.未预配套;
                    }
                    //else
                    //{
                    //    throw new UserFriendlyException("数量不匹配请检查");
                    //}
                    var listNew = ObjectMapper.Map<StoreStock>(storeStockContentList);
                    await _storeStockpository.UpdateAsync(listNew);
                }
            }
        }
        /// <summary>
        ///  外部调用配套预配套汇总
        /// </summary>
        /// <param name="xjName"></param>
        /// <param name="xjNo"></param>
        /// <param name="ModelId">型号Id</param>
        /// <param name="LotNoId">发次Id</param>
        /// <returns></returns>
        public List<MatingExternalCallDto> GetExternalCall(string xjName, string xjNo, Guid? ModelId, Guid? LotNoId)
        {
            //获取汇总bom
            var collectManagerList = _collectBomManagerRepository.FirstOrDefaultAsync(t => t.XJName == xjName && t.XJDrawingNo == xjNo && t.ModuleId == ModelId.Value && t.SendTimeId == LotNoId.Value).Result;
            if (collectManagerList == null)
            {
                return new List<MatingExternalCallDto>();
            }
            //var queryBomDesignXj = _bomDesignDetailRepository.FirstOrDefaultAsync(t => t.Id == collectManagerList.XJId && t.ParentId == Guid.Empty).Result;
            //if (queryBomDesignXj != null)
            //{

            //}
            //找出BomdesignId 根据bomdesignID 找出芯级下的所有物料
            //var queryBomDesignData = _collectBomManagerChildRepository.GetAll().Where(t => t.BomDesignId == collectManagerList.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件 && t.LevelRelationship.StartsWith(queryBomDesignXj.LevelRelationship));
            var queryBomDesignData = _collectBomAppService.GetCollectBomMaterialsContent(collectManagerList.XJId);

            //计算预配套数量 汇总
            var materalisAnalyseCount = from groupAnalyseContent in (from queryMaterislsContent in _materialsContentRepository.GetAll()
                                                                     join queryStoreStocks in _storeStockpository.GetAll() on queryMaterislsContent.Id equals queryStoreStocks.MaterialsContentId
                                                                     join queryStoreStockContents in _storeStockContentRepository.GetAll().Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.BomAnalysecontentId == collectManagerList.Id && (DateTime.Parse(t.ExpirationDate)) > DateTime.Now) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                     join bomDesignDetailData in queryBomDesignData on queryMaterislsContent.Id equals bomDesignDetailData.MerialsId
                                                                     select new MatingExternalCallDto
                                                                     {
                                                                         MaterialsContentId = queryMaterislsContent.Id
                                                                     })
                                        group groupAnalyseContent by new { groupAnalyseContent.MaterialsContentId } into groupByData
                                        select new MatingExternalCallDto
                                        {
                                            MaterialsContentId = groupByData.Key.MaterialsContentId,
                                            PreSuiteStockAll = groupByData.Count()
                                        };

            var materalisMatingCount = from groupAnalyseContent in (from queryMaterislsContent in _materialsContentRepository.GetAll()
                                                                    join queryStoreStocks in _storeStockpository.GetAll() on queryMaterislsContent.Id equals queryStoreStocks.MaterialsContentId
                                                                    join queryStoreStockContents in _storeStockContentRepository.GetAll().Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.BomAnalysecontentId == collectManagerList.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                    //into bo
                                                                    //      from boms in bo.DefaultIfEmpty()
                                                                    //join bomDesignDetailData in queryBomDesignData on queryMaterislsContent.Id equals bomDesignDetailData.MaterialId
                                                                    //into ma
                                                                    //      from mac in ma.DefaultIfEmpty()
                                                                    select new MatingExternalCallDto
                                                                    {
                                                                        MaterialsContentId = queryMaterislsContent.Id
                                                                    })
                                       group groupAnalyseContent by new { groupAnalyseContent.MaterialsContentId } into groupByData
                                       select new MatingExternalCallDto
                                       {
                                           MaterialsContentId = groupByData.Key.MaterialsContentId,
                                           SuiteStockAll = groupByData.Count()
                                       };

            var calcAll = from materalisAnalyse in materalisAnalyseCount
                          join materalisMating in materalisMatingCount on materalisAnalyse == null ? Guid.Empty : materalisAnalyse.MaterialsContentId equals
                         materalisMating == null ? Guid.Empty : materalisMating.MaterialsContentId into ma
                          from mac in ma.DefaultIfEmpty()
                          select new MatingExternalCallDto
                          {
                              MaterialsContentId = materalisAnalyse.MaterialsContentId,
                              PreSuiteStockAll = materalisAnalyse.PreSuiteStockAll,
                              SuiteStockAll = mac == null ? 0 : mac.SuiteStockAll,
                              DifferenceCount = materalisAnalyse.PreSuiteStockAll - (mac == null ? 0 : mac.SuiteStockAll)
                          };

            if (calcAll != null && calcAll.Count() > 0)
            {
                return calcAll.ToList();
            }
            return new List<MatingExternalCallDto>();
        }
    }
}
